package com.demo.ordered;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

public class OrderedProducer {
    public static void main(String[] args) throws Exception {
        //Instantiate with a producer group name.
        MQProducer producer = new DefaultMQProducer("ordered_group");
        //Launch the instance.
        producer.start();
        String[] tags = new String[] {"吃饭", "睡觉", "打豆豆"};
        for (int i = 100; i > 0; i--) {
            for (int j = 0; j < tags.length; j++) {
                Message msg = new Message("ordered_topic",
                        tags[j], "KEY" + i,
                        ("企鹅-" + i+" 要 " + tags[j]).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        Integer id = (Integer) arg;
                        int index = id % mqs.size();
                        return mqs.get(index);
                    }
                }, i);
                System.out.printf("%s%n", sendResult);

            }
        }
        //server shutdown
        producer.shutdown();
    }
}